// pages/notice/notice.js
import throttle from '../../utils/throttle.js';
import { hasPermission } from '../../utils/tools';
import Http from '../../utils/http.js';
const http = new Http();
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        //tabbar背景
        tabbarlist: [
            {
                text: '地图',
                num: 0,
            },
            {
                text: '通答',
                num: 0,
            },
            {
                text: '经验',
                num: 0,
            },
            {
                text: '我的',
                num: 0,
            },
        ],
        tabbarActive: 1,
        // 右上角胶囊的高度
        buttonHeight: '',
        // 右上角胶囊据顶部高度
        buttonTop: '',
        // 外部scroll-view滚动高度
        scrollTop: 0,
        // 外部滚动高度
        scrollHeight: '',
        // 内部scroll-view是否可以滚动
        canScroll: false,
        projectsArr: [],
        noticeArr: [],
        pageNo: 0,
        loading: false,
        loadingAll: false,
        // 更多操作
        show: false,
        actions: [
            {
                id: '00',
                name: '编辑',
                color: '#333333',
            },
            {
                id: '01',
                name: '删除',
                color: '#ff455e',
            },
        ],
        // 长按当前通告的id
        activeNoticeId: '',
        // 长按当前通告的发布人id
        activeCreateUid: '',
        // 是否显示添加项目组
        showAddProjectTeam: false,
        // 下拉刷新
        refreshing: false,
        tabsArr: ['项目通告', '互动问答'],
        currentTabIndex: 0,
        // 问题数组
        questionArr: [],
        // 问题分页
        questionPageNum: 0,
        // 互动问答列表loading
        questionLoading: false,
        questionloadingAll: false,
        // 互动问答总数
        questionTotal: 0,
        activeQuestionId: '',
        // '00'是通告，'01'是问答
        flg: null,
        // 点击的通告
        clickNoticeIndex: null,
        // 点击的互动问答
        clickQuestionIndex: null,
        permissionList: ['00', '01'],
        newsCount: 0,
        // 点击标题回到顶部
        toView: '',
        toViewPage: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            showAddProjectTeam: hasPermission(this.data.permissionList),
        });

        this.refreshProject();
        this.getProjectNoticeList();
        this.getProjectQuestionList();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        //tabbar
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 1,
            });
            this.getTabBar().refresh();
        }
        this.refreshProject();
        this.getNewsNum();
    },

    pullDown: function () {
        this.setData({
            refreshing: true,
        });
        this.getFirstPageProjectNotice();
        this.getFirstPageProjectQuestion();
        this.refreshProject();
        this.getNewsNum();
    },

    // 从自定义导航栏组件中获取气泡信息
    getMenuButtonBoundingClientRect(e) {
        console.log(e.detail);
        this.setData({
            buttonHeight: e.detail.height,
            buttonTop: e.detail.top,
        });
        let removeHeight = e.detail.top + e.detail.height + 5;
        this.getScrollHeight(removeHeight);
    },

    getScrollHeight(removeHeight) {
        var that = this;
        wx.getSystemInfo({
            success: function (res) {
                let clientHeight = res.windowHeight,
                    scrollHeight;
                // 页面高度减去需要删除的高度
                scrollHeight = clientHeight - removeHeight;

                that.setData({
                    scrollHeight: scrollHeight,
                });
            },
        });
    },

    // 获取项目组列表
    getProjectTeamList() {
        let _that = this;
        http.getRequest(
            `cjMap/getProjectTeamList?authId=${app.globalData.authId}`
        ).then((res) => {
            if (res.status == 0) {
                res.data.map((item) => {
                    item.pjteamlogopicurl = item.pjteamlogopicurl.replace(
                        /\/0_/,
                        '/1_'
                    );
                });
                _that.setData({
                    projectsArr: res.data,
                });
            }
        });
    },

    // 获取所有项目通告
    getProjectNoticeList() {
        let _that = this;
        if (!_that.data.loadingAll && !_that.data.loading) {
            _that.setData({
                pageNo: _that.data.pageNo + 1,
                loading: true,
                loadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pageSize: 15,
                pageNo: _that.data.pageNo,
            };
            http.getRequest(`cjMap/getProjectNoticeList`, data).then((res) => {
                if (res.status == 0) {
                    res.data.map((notice) => {
                        // 使用缩略图
                        notice.coverpicurl = notice.coverpicurl.replace(
                            /\/0_/,
                            '/1_'
                        );
                        // 格式化时间
                        notice.createtime = app.timeago(notice.createtime);
                        _that.data.noticeArr.push(notice);
                    });
                    _that.setData({
                        noticeArr: _that.data.noticeArr,
                        loading: false,
                        refreshing: false,
                    });

                    if (res.pager.currentPage >= res.pager.totalPages) {
                        _that.setData({
                            loadingAll: true,
                        });
                    }
                } else {
                    _that.setData({
                        loadingAll: true,
                        loading: false,
                    });
                }
            });
        }
    },

    // 获取第一页项目通告
    getFirstPageProjectNotice() {
        let _that = this;
        _that.setData({
            pageNo: 1,
            loading: true,
            loadingAll: false,
        });
        let data = {
            authId: app.globalData.authId,
            pageSize: 15,
            pageNo: 1,
        };
        http.getRequest(`cjMap/getProjectNoticeList`, data).then((res) => {
            if (res.status == 0) {
                let tempArr = [];
                res.data.map((notice) => {
                    // 使用缩略图
                    notice.coverpicurl = notice.coverpicurl.replace(
                        /\/0_/,
                        '/1_'
                    );
                    // 格式化时间
                    notice.createtime = app.timeago(notice.createtime);
                    tempArr.push(notice);
                });
                _that.setData({
                    noticeArr: tempArr,
                    loading: false,
                    refreshing: false,
                });

                if (res.pager.currentPage >= res.pager.totalPages) {
                    _that.setData({
                        loadingAll: true,
                    });
                }
            } else {
                _that.setData({
                    loadingAll: true,
                    loading: false,
                });
            }
        });
    },

    // 刷新
    refresh() {
        this.setData(
            {
                pageNo: 0,
                loading: false,
                loadingAll: false,
                noticeArr: [],
            },
            () => {
                this.getProjectNoticeList();
            }
        );
    },

    // 刷新项目组列表
    refreshProject() {
        this.getProjectTeamList();
    },

    // 长按编辑
    edit(e) {
        let { id, createuid, flg, projectauthority } = e.currentTarget.dataset;

        if (flg === '00') {
            // 说明是通告
            // 管理员或者本人发的通告或者项目组组长（只有项目组组长和组员可以发通告）
            if (
                hasPermission(this.data.permissionList, createuid) ||
                projectauthority == '02'
            ) {
                // 修改导航栏颜色
                wx.setNavigationBarColor({
                    frontColor: '#000000',
                    backgroundColor: '#484848',
                    animation: {
                        duration: 300,
                        timingFunc: 'easeIn',
                    },
                });
                this.setData({
                    show: true,
                    activeNoticeId: id,
                    flg: '00',
                    activeCreateUid: createuid,
                });
            } else {
                return;
            }
        } else {
            // 说明是问题
            // 互动问答是所有人可以发布，该项目组组长可以编辑
            if (
                hasPermission(this.data.permissionList, createuid) ||
                projectauthority == '02'
            ) {
                // 修改导航栏颜色
                wx.setNavigationBarColor({
                    frontColor: '#000000',
                    backgroundColor: '#484848',
                    animation: {
                        duration: 300,
                        timingFunc: 'easeIn',
                    },
                });
                this.setData({
                    show: true,
                    activeQuestionId: id,
                    flg: '01',
                    activeCreateUid: createuid,
                });
            } else {
                return;
            }
        }
        // 隐藏tabbar
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                tabbarShow: false,
            });
        }
    },

    // 取消编辑
    onCancel() {
        this.setData(
            {
                show: false,
            },
            () => {
                if (typeof this.getTabBar === 'function' && this.getTabBar()) {
                    this.getTabBar().setData({
                        tabbarShow: true,
                    });
                }
            }
        );
    },

    // 选中后
    onSelect(e) {
        console.log(e);
        let _that = this;
        if (_that.data.flg === '00') {
            if (e.detail.id === '00') {
                _that.onCancel();
                wx.navigateTo({
                    url: `../../releasePage/pages/announcePublish/announcePublish?noticeId=${_that.data.activeNoticeId}`,
                });
            } else if (e.detail.id === '01') {
                _that.onCancel();
                wx.showModal({
                    title: '确认删除？',
                    content: '',
                    success: function (res) {
                        if (res.confirm) {
                            _that.deleteNotice(_that.data.activeNoticeId);
                        } else {
                            console.log('取消操作');
                        }
                    },
                });
            }
        } else if (_that.data.flg === '01') {
            if (e.detail.id === '00') {
                _that.onCancel();
                wx.navigateTo({
                    url: `../../releasePage/pages/publishQuestion/publishQuestion?questionId=${_that.data.activeQuestionId}`,
                });
            } else if (e.detail.id === '01') {
                _that.onCancel();
                wx.showModal({
                    title: '确认删除？',
                    content: '',
                    success: function (res) {
                        if (res.confirm) {
                            _that.deleteQuestion(_that.data.activeQuestionId);
                        } else {
                            console.log('取消操作');
                        }
                    },
                });
            }
        }
    },

    deleteNotice(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/deleteProjectNotice',
            data: {
                authId: app.globalData.authId,
                id: id,
            },
            success(res) {
                if (res.data.status === '0') {
                    // 取消弹框
                    _that.onCancel();
                    // 删除成功后就刷新
                    _that.refresh();
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 1500,
                    });
                } else {
                    console.log('删除失败');
                }
            },
        });
    },

    deleteQuestion(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/deleteProjectQuestion',
            data: {
                authId: app.globalData.authId,
                id: id,
            },
            success(res) {
                if (res.data.status === '0') {
                    // 取消弹框
                    _that.onCancel();
                    // 删除成功后就刷新问题列表
                    _that.refreshQuestion();

                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 1500,
                    });
                } else {
                    console.log('删除失败');
                }
            },
        });
    },

    changeNav: throttle(
        function (e) {
            let { nav, index } = e.currentTarget.dataset;
            if (this.data.currentTabIndex === 0) {
                this.setData({
                    clickNoticeIndex: index,
                });
            } else {
                this.setData({
                    clickQuestionIndex: index,
                });
            }

            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    onTabsClick(e) {
        this.setData({
            currentTabIndex: e.detail.index,
        });
    },

    swiperChange(e) {
        this.setData({
            currentTabIndex: e.detail.current,
        });
    },

    // 获取互动问答
    getProjectQuestionList() {
        let _that = this;
        if (!_that.data.questionloadingAll && !_that.data.questionLoading) {
            _that.setData({
                questionPageNum: _that.data.questionPageNum + 1,
                questionLoading: true,
                questionloadingAll: false,
            });
            let data = {
                authId: app.globalData.authId,
                pjteamid: '',
                pageSize: 20,
                pageNo: _that.data.questionPageNum,
            };
            http.getRequest(`cjMap/getProjectQuestionList`, data).then(
                (res) => {
                    if (res.status == 0) {
                        res.data.map((question) => {
                            question.createtime = app.timeago(
                                question.createtime
                            );
                            _that.data.questionArr.push(question);
                        });
                        _that.setData({
                            questionArr: _that.data.questionArr,
                            questionLoading: false,
                            questionTotal: res.pager.totalRows,
                        });

                        if (res.pager.currentPage >= res.pager.totalPages) {
                            _that.setData({
                                questionloadingAll: true,
                            });
                        }
                    } else {
                        _that.setData({
                            questionloadingAll: true,
                            questionLoading: false,
                        });
                    }
                }
            );
        }
    },

    // 获取第一页互动问答
    getFirstPageProjectQuestion() {
        let _that = this;
        _that.setData({
            questionPageNum: 1,
            questionLoading: true,
            questionloadingAll: false,
        });
        let data = {
            authId: app.globalData.authId,
            pjteamid: '',
            pageSize: 20,
            pageNo: 1,
        };
        http.getRequest(`cjMap/getProjectQuestionList`, data).then((res) => {
            if (res.status == 0) {
                let tempArr = [];
                res.data.map((question) => {
                    question.createtime = app.timeago(question.createtime);
                    tempArr.push(question);
                });
                _that.setData({
                    questionArr: tempArr,
                    questionLoading: false,
                    questionTotal: res.pager.totalRows,
                });

                if (res.pager.currentPage >= res.pager.totalPages) {
                    _that.setData({
                        questionloadingAll: true,
                    });
                }
            } else {
                _that.setData({
                    questionloadingAll: true,
                    questionLoading: false,
                });
            }
        });
    },
    // 刷新问题
    refreshQuestion() {
        this.setData(
            {
                questionPageNum: 0,
                questionLoading: false,
                questionloadingAll: false,
                questionArr: [],
            },
            () => {
                this.getProjectQuestionList();
            }
        );
    },

    // 获取外部滚动高度
    getScrollTop(e) {
        if (e.detail.scrollTop < 250) {
            this.setData({
                canScroll: false,
            });
        } else {
            this.setData({
                canScroll: true,
            });
        }
    },

    // 刷新文字变灰
    handleRead() {
        const property = `noticeArr[${this.data.clickNoticeIndex}].readflg`;
        this.setData({
            [property]: '01',
        });
    },

    // 刷新互动问答文字变灰
    handleQuestionRead() {
        const property = `questionArr[${this.data.clickQuestionIndex}].readflg`;
        this.setData({
            [property]: '01',
        });
    },

    // 获取消息数量
    getNewsNum() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getUnreadMsgCnt',
            header: {
                'content-type': 'application/json',
            },
            data: {
                authId: app.globalData.authId,
            },
            success(res) {
                console.log(res.data.data);
                app.globalData.nqModuleCount = res.data.data.nqModuleCount;
                app.globalData.exModuleCount = res.data.data.exModuleCount;
                app.globalData.mineModuleCount = res.data.data.mineModuleCount;
                let arr1 = 'tabbarlist[1].num';
                let arr2 = 'tabbarlist[2].num';
                let arr3 = 'tabbarlist[3].num';
                _that.setData({
                    [arr1]: res.data.data.nqModuleCount,
                    [arr2]: res.data.data.exModuleCount,
                    [arr3]: res.data.data.mineModuleCount,
                    newsCount: res.data.data.nqCount,
                });
                if (
                    typeof _that.getTabBar === 'function' &&
                    _that.getTabBar()
                ) {
                    _that.getTabBar().setData({
                        selected: 1,
                        tabbarShow: true,
                    });
                    _that.getTabBar().refresh();
                }
            },
        });
    },
    onTabbarChange(event) {
        this.setData({ active: event.detail });
        let url;
        if (event.detail == 0) {
            url = '/pages/index/index';
        }
        if (event.detail == 1) {
            url = '/pages/notice/notice';
        }
        if (event.detail == 2) {
            url = '/pages/experience/experience';
        }
        if (event.detail == 3) {
            url = '/pages/minePage/minePage';
        }
        wx.switchTab({
            url: url,
        });
    },
    // 点击标题回到顶部
    doubleTap() {
        if (this.data.currentTabIndex == 1) {
            this.setData({
                toView: 'question',
                toViewPage: 'projects-area',
            });
        } else {
            this.setData({
                toView: 'notice',
                toViewPage: 'projects-area',
            });
        }
    },
});
